<template>
    <div v-loading="loading" @click="SetingDay" class="ScheduleProgressRoot">
        <el-progress type="circle" :percentage="showNum" :color="colors" />
        <div class="showData">
            <div class="title"><el-text>距离<span class="DayValue target"> <br>
                    <transition name="el-fade-in-linear"><span v-show="target"> {{ target }}</span> </transition> <br>
                </span>还有</el-text></div>
            <div class="Day">
                <span class="DayValue">{{ Math.abs(ShowValue) }}</span><el-text>天</el-text>
            </div>
        </div>
    </div>

    <!-- 目标设置界面 -->
    <el-dialog v-model="showSetingDayView" title="设置目标" width="80%">
        <span>
            <OptionTarget ref="OptionTargetRef" :target_name="target" :colors="colors" />
        </span>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="showSetingDayView = false">取消</el-button>
                <el-button type="primary" @click="OptionTargetOk">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup>
import { ref, reactive, watch, onMounted, computed } from "vue"
import * as UI from "@element-plus/icons-vue"
import { ElMessage } from 'element-plus'
import OptionTarget from "@/components/ScheduleProgress/OptionTarget.vue";
import Axios from 'axios';
import { useStore } from "vuex";
const store = useStore()
let StartTimeDay = ref("")  //计时开始日
let EndTimeDay = ref("");   //结束日,不要改初始值
let target = ref("");   // 目标
let showNum = ref(0);	// 显示百分比,不要改初始值
let Num = ref(0);       //实际百分比
let loading = ref(true)	// 加载
let DayValue = ref(0);   // 剩余天数 
let ShowValue = ref(0)  // 显示的剩余天数，默认值锁定为-1，不可改，如果要改，改上面的值就行,刷新要调用
let showSetingDayView = ref(false);  // 设置界面的显示
let OptionTargetRef = ref(null);    // OptionTargetRef组件
let NetworkError_showTime = "2024-12-19"

function getNum(){
    let now = new Date().getTime();
    let start_time_num = new Date(StartTimeDay.value).getTime();
    let end_time_num = new Date( EndTimeDay.value ).getTime();
    let useTime =    now - start_time_num;
    let allTime = end_time_num - start_time_num;
    let res = (useTime / allTime)*100;
    return res
}

// 获取网络数据
async function get_netWorkData() {
    // 初始化
    loading.value = true
    // 网络请求主体
    let url = "http://" + store.state.ip + ":" + store.state.port + "/get_user_target_data"
    await Axios.get(url)
        .then(function (response) {
            // 处理成功的响应

            target.value = response.data.data.target_name;  // 最大 8 个字
            EndTimeDay.value = response.data.data.target_time;
            colors = colorStringtoColors(response.data.data.color_theme)
            StartTimeDay.value = response.data.data.start_time
            Num.value = getNum()
            
        }).catch((e) => {
            console.error(e);
            target.value = "网络错误"
            EndTimeDay.value = NetworkError_showTime;
        })
    // 刷新
    loading.value = false;
    ShowValue.value -= 1;       //让watch的监控开始运行
    showNum.value += 1;
}

watch(EndTimeDay, (newValue) => {
    let now = new Date();
    if (newValue == '') {
        // 此为EndTimeDay没有初始值的情况
    } else {
        let EndTime = new Date(newValue)
        // 计算两个日期的毫秒差值
        let diffInMilliseconds = Math.abs(now - EndTime);
        let Day = Math.ceil(diffInMilliseconds / (1000 * 60 * 60 * 24));
        DayValue.value = Day;
    }

})

// 百分比快速过渡
watch(showNum, (newValue) => {
    let speed = 0.1
    if (newValue > Num.value) {
        setTimeout(() => {
            showNum.value -= 1;
        }, speed);
    }
    if (newValue < Num.value) {
            showNum.value += 1;
    }
})

// 剩余天数文字快速过度 延时设置为0则不启用
watch(ShowValue, (newValue, oldValue) => {
    
    if (newValue < DayValue.value) {
        if (DayValue.value < 10) {
            setTimeout(() => {
                ShowValue.value += 1;
            }, 50);  // 在这里设置
        } else if (DayValue.value < 50) {
            setTimeout(() => {
                ShowValue.value += 1;
            }, 10);  // 在这里设置
        } else {
            setTimeout(() => {
                ShowValue.value += 1;
            }, 0);  // 在这里设置
        }
    }
    if(newValue > DayValue.value){
        ShowValue.value = 0;
    }
})

get_netWorkData();

function SetingDay() {
    // 加载完成才可以点击
    if (loading.value == false) {
        showSetingDayView.value = true;
    }
}


//不同进度的颜色
let colors = reactive([
    { color: '#f56c6c', percentage: 20 },
    { color: '#e6a23c', percentage: 40 },
    { color: '#5cb87a', percentage: 60 },
    { color: '#1989fa', percentage: 80 },
    { color: '#6f7ad3', percentage: 100 },
])
// 生成可以传给后端的颜色主题字符串
function colortoString(colors) {
    let res = []
    for (let i = 0; i < colors.length; i++) {
        // [{ color: '#f56c6c', percentage: 20 },{ color: '#e6a23c', percentage: 40 },{ color: '#5cb87a', percentage: 60 },{ color: '#1989fa', percentage: 80 },{ color: '#6f7ad3', percentage: 100 }]
        let tmp_color = colors[i].color;
        let tmp_percentage = colors[i].percentage;
        let strObject = "color:" + tmp_color + "| percentage:" + tmp_percentage + ""
        res.push(strObject)
    }
    return res
}
function colorStringtoColors(ColorString) {
    ColorString = ColorString.split(",")
    let res = []
    for (let i = 0; i < ColorString.length; i++) {
        let tmp_object = {}
        tmp_object.color = ColorString[i].split("|")[0].split(":")[1]
        tmp_object.percentage = ColorString[i].split("|")[1].split(":")[1]
        res.push(tmp_object)
    }
    return res

}

// 设置目标的确定界面
// 这个函数需要定义在onMounted函数外，内容我卸载onMounted内了
let OptionTargetOk;

onMounted(() => {

    //设置界面确定函数
    OptionTargetOk = async () => {
        if (OptionTargetRef.value['EndTime'] == '' ||
            OptionTargetRef.value['TargetName'] == '' ||
            OptionTargetRef.value['StartTime'] == '' ||
            OptionTargetRef.value['StartTimeMinToEndTimeTip'] ||
            OptionTargetRef.value['TargetName'].length > OptionTargetRef.value['textTipMaxLength']
        ) {
            ElMessage.error('错误，请检查您的填写是否有问题')
        } else {
            colors = OptionTargetRef.value["userSelect_color"]
            
            let url = "http://" + store.state.ip + ":" + store.state.port + "/set_user_target_data"
            await Axios.post(url = url, {
                data: {
                    target_name: OptionTargetRef.value['TargetName'],
                    target_time: OptionTargetRef.value['EndTime'],
                    color_theme: colortoString(colors),
                    start_time: OptionTargetRef.value['StartTime']
                }
            }, {
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            // 让设置界面关闭
            showSetingDayView.value = false
            // 下面是网络请求
            // code
            // 网络刷新
            get_netWorkData();
        }
    }
})

</script>
<style lang="less" scoped>
.ScheduleProgressRoot {
    display: grid;
    grid-template-columns: 1fr 1fr;
    padding: 5%;
    border: 20px;

    .showData {
        text-align: center;
        display: grid;
        grid-template-rows: 2fr 1fr;

        .title {
            font-weight: bolder;
            font-size: 0.8em;

            .DayValue {
                font-size: calc(1.2vw + 1.4vh + 0.6vmin);
            }
        }

        .Day {
            font-weight: bolder;
            font-size: 1.2em;
        }
    }

    .SetDay {
        margin-top: 10%;

        .SetDayButton {
            width: 100%;
        }
    }
}

.el-loading-mask {
    border-radius: 20px !important;
}

.DayValue {
    color: var(--el-color-primary);
}
</style>